import * as echarts from 'echarts'
import resize from '@/components/Charts/mixins/resize'
import { previewDataInterface } from '@/api/systemData/dataInterface'

export default {
  mixins: [resize],
  props: {
    title: { type: String, default: '' },
    cuKey: { type: String, default: '' },
    dataType: { type: String, default: 'static' },
    propsApi: { type: String, default: '' },
    option: { type: Object, default: () => {} }
  },
  data() {
    return {
      chart: null,
      currOption: {},
      isEmpty: true
    }
  },
  mounted() {
    if (this.dataType === 'dynamic') {
      if (!this.propsApi) return
      previewDataInterface(this.propsApi).then(res => {
        if (res.data.length == 0) {
          this.isEmpty = true
        } else if (this.cuKey == 'pieChart') {
          this.currOption = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            toolbox: {
              feature: {
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            legend: {
              orient: 'vertical',
              x: 'left',
              formatter: function(name) {
                var index = 0
                var clientlabels = res.data.map(o => {
                  return o.category
                })
                var clientcounts = res.data.map(o => {
                  return o.numerical
                })
                clientlabels.forEach(function(value, i) {
                  if (value == name) {
                    index = i
                  }
                })
                return name + ':' + clientcounts[index]
              }
            },
            series: [
              {
                name: '销售额',
                type: 'pie',
                center: ['50%', '50%'],
                selectedMode: 'single',
                data: res.data.map(o => {
                  return { name: o.category, value: o.numerical }
                }),
                label: {
                  normal: {
                    formatter: '{b}:({d}%)',
                    textStyle: {
                      fontWeight: 'normal',
                      fontSize: 15
                    }
                  }
                },
                itemStyle: {
                  emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
        } else if (this.cuKey == 'lineChart') {
          var legend = []
          res.data.map(item => {
            if (legend.indexOf(item.r_legend) == -1) {
              legend.push(item.r_legend)
            }
          })
          var xAxis = []
          res.data.map(item => {
            if (xAxis.indexOf(item.r_xAxis) == -1) {
              xAxis.push(item.r_xAxis)
            }
          })
          console.log(legend, 'legend')
          this.option.legend.data = legend
          this.option.xAxis[0].data = xAxis
          var self = this
          this.option.tooltip.formatter = function(params, ticket, callback) {
            for (var i = 0; i < params.length; i++) {
              for (var j = params.length - 1; j > i; j--) {
                if (params[j].data == params[i].data) {
                  params.splice(j, 1)
                  break
                }
              }
            }
            var tip = params[0].name + '：<br />'
            for (var i = 0; i < params.length; i++) {
              //这里是自己定义样式， params[i].marker 表示是否显示左边的那个小圆圈
              if (params[i].value != 0) {
                let seriesName = params[i].seriesName
                let name = params[i].name
                var result = res.data.filter(i => i.r_legend == seriesName && i.r_xAxis == name)
                tip = tip + params[i].marker + params[i].seriesName + ':' + params[i].value + self.option.series[i].unit + (result.length == [] ? '' : result[0]['r_note'] == '' ? '' : ' (' + result[0]['r_note'] + ')') + '<br/>'
              }
            }
            return tip
          }
          legend.map((item, index) => {
            this.option.series[index].name = item
            this.option.series[index].data = xAxis.map(item1 => {
              var result = res.data.filter(i => i.r_legend == item && i.r_xAxis == item1)
              return result.length > 0 ? result[0].r_number : 0
            })
          })
          this.currOption = this.option
        }
        this.resetChart()
      })
    } else {
      this.currOption = this.option
      this.initChart()
    }
  },
  watch: {
    option: {
      handler(val) {
        this.currOption = val
        this.resetChart()
      },
      deep: true
    },

    dataType(val) {
      if (val !== 'dynamic') {
        this.currOption = this.option
        this.resetChart()
      }
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chart) {
        console.warn('Chart container element not found')
        return
      }
      
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(this.currOption)
      setTimeout(() => {
        this.$nextTick(() => {
          if (this.chart) {
            this.chart.resize()
          }
        })
      }, 50)
    },
    resetChart() {
      this.isEmpty = JSON.stringify(this.currOption) === '{}'
      this.chart && this.chart.dispose()
      this.chart = null
      if (!this.isEmpty) this.initChart()
    }
  },
  beforeDestroy() {
    if (!this.chart) return
    this.chart.dispose()
    this.chart = null
  }
}
